import os
import shutil
from flask import current_app
import datetime

class StorageService:
    """存储服务类"""
    
    @staticmethod
    def get_storage_stats():
        """
        获取存储统计信息
        
        Returns:
            dict: 存储统计信息
        """
        upload_folder = current_app.config['UPLOAD_FOLDER']
        
        # 计算录音文件数量和总大小
        recordings_count = 0
        total_storage = 0
        last_recording_time = None
        
        if os.path.exists(upload_folder):
            for filename in os.listdir(upload_folder):
                file_path = os.path.join(upload_folder, filename)
                if os.path.isfile(file_path):
                    recordings_count += 1
                    total_storage += os.path.getsize(file_path)
                    file_mtime = os.path.getmtime(file_path)
                    if last_recording_time is None or file_mtime > last_recording_time:
                        last_recording_time = file_mtime
        
        # 获取磁盘使用情况
        if os.path.exists(upload_folder):
            total, used, free = shutil.disk_usage(upload_folder)
        else:
            total, used, free = 0, 0, 0
            
        return {
            'recordings_count': recordings_count,
            'total_storage': total_storage,
            'total_storage_readable': StorageService._get_readable_size(total_storage),
            'last_recording_at': datetime.datetime.fromtimestamp(last_recording_time).isoformat() if last_recording_time else None,
            'updated_at': datetime.datetime.now().isoformat(),
            'disk_total': total,
            'disk_total_readable': StorageService._get_readable_size(total),
            'disk_used': used,
            'disk_used_readable': StorageService._get_readable_size(used),
            'disk_free': free,
            'disk_free_readable': StorageService._get_readable_size(free),
            'disk_usage_percent': round(used / total * 100, 2) if total > 0 else 0
        }
    
    @staticmethod
    def cleanup_orphaned_files():
        """
        清理孤立文件（不再需要的文件）
        
        Returns:
            dict: 清理结果
        """
        upload_folder = current_app.config['UPLOAD_FOLDER']
        if not os.path.exists(upload_folder):
            return {'status': 'error', 'message': '上传目录不存在'}
            
        # 在没有数据库的情况下，我们无法确定哪些是孤立文件
        # 这里只返回一个模拟结果
        return {
            'status': 'success',
            'deleted_count': 0,
            'deleted_size': 0,
            'deleted_size_readable': StorageService._get_readable_size(0),
            'message': '在没有数据库的情况下，无法确定孤立文件'
        }
    
    @staticmethod
    def _get_readable_size(size_bytes):
        """
        获取可读的文件大小
        
        Args:
            size_bytes: 文件大小（字节）
            
        Returns:
            str: 可读的文件大小
        """
        if size_bytes == 0:
            return "0 B"
            
        size_names = ("B", "KB", "MB", "GB", "TB")
        i = 0
        while size_bytes >= 1024 and i < len(size_names) - 1:
            size_bytes /= 1024
            i += 1
            
        return f"{size_bytes:.2f} {size_names[i]}" 